import { ref, onMounted, onUnmounted } from 'vue'

export function useInfiniteScroll(loadMore, options = {}) {
  const {
    threshold = 100,
    immediate = true
  } = options

  const loading = ref(false)
  const finished = ref(false)

  const handleScroll = async () => {
    if (loading.value || finished.value) return

    const scrollHeight = document.documentElement.scrollHeight
    const scrollTop = document.documentElement.scrollTop
    const clientHeight = document.documentElement.clientHeight

    if (scrollHeight - scrollTop - clientHeight < threshold) {
      loading.value = true
      try {
        const hasMore = await loadMore()
        finished.value = !hasMore
      } finally {
        loading.value = false
      }
    }
  }

  onMounted(() => {
    if (immediate) {
      handleScroll()
    }
    window.addEventListener('scroll', handleScroll)
  })

  onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll)
  })

  return {
    loading,
    finished
  }
} 